# Untitled - By: lenovo - Thu Jul 25 2024

import sensor
import image
from pyb import UART


# sensor 初始化
sensor.reset()
# sensor初始配置
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames()
# 颜色捕捉时,设置为False
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)


# 创建串口通信对象
uart = UART(3, 115200, bits=8, parity=None, stop=1)
# 创建image对象
img = sensor.snapshot()
# 创建检测区间
# 该框原点坐标
findLen = [160, 150]
subXY = [(img.width() // 2) - (findLen[0] // 2), (img.height() // 2) - (findLen[1] // 2)]
scope = [subXY[0], subXY[1], findLen[0], findLen[1]]


# 绘制识别到的矩形
def DrawRecognize(recognize):
    global img
    img.draw_rectangle(recognize.rect())
#    for XY in recognize.corners():
#        img.draw_circle(XY[0], XY[1], 5, color=(0, 255, 0))
    XY = recognize.corners()
    img.draw_circle(XY[0][0], XY[0][1], 5, color=(255, 0, 0))
    img.draw_circle(XY[1][0], XY[1][1], 5, color=(0, 255, 0))
    img.draw_circle(XY[2][0], XY[2][1], 5, color=(0, 0, 255))
    img.draw_circle(XY[3][0], XY[3][1], 5, color=(255, 255, 255))


# 发送坐标数据
def UARTSendRecognizeInfo(qrcode):
    global uart
    uart.write(qrcode.payload())
    print(qrcode.payload())
    for XY in qrcode.corners():
#        从左上角开始顺时针返回坐标
        sendarray = str(XY[0]) + ' ' + str(XY[1])
#        uart.write(sendarray)
        print(sendarray)
    print('')


# 运行开始处
while True:
    img = sensor.snapshot()
#    去畸变
    img.lens_corr(strength=1.8, zoom=1.0)
    img.draw_rectangle(scope, thickness=1)

    for elem in img.find_qrcodes(roi=scope):
        # 将找到的二维码进行标记
        DrawRecognize(elem)
        # 发送坐标数据
        UARTSendRecognizeInfo(elem)
